package redis

import (
	"cart_srv/cart"
	"context"
	"fmt"
	"strconv"
)

const GoodsStock = "goods_stock:goods_id_"

func SyncStock(GoodsId int64, Stock int64) {
	key := GoodsStock + fmt.Sprintf("%d", GoodsId)
	for i := 0; i < int(Stock); i++ {
		Client.LPush(context.Background(), key, GoodsId)
	}
}

func GetStock(GoodsId int64) int64 {
	key := GoodsStock + fmt.Sprintf("%d", GoodsId)
	return Client.LLen(context.Background(), key).Val()
}

func AddCart(Map map[string]interface{}) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", Map["user_id"], Map["goods_id"])
	return Client.HMSet(context.Background(), key, Map).Err()
}

func Exists(userid, goodsid int64) bool {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userid, goodsid)
	return Client.Exists(context.Background(), key).Val() == 1
}

func UpdateCart(userid, goodsid, num int64) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userid, goodsid)
	return Client.HIncrBy(context.Background(), key, "num", num).Err()
}

func CartList(userid int64) (shopList []*cart.ShopList, err error) {
	key := fmt.Sprintf("cart:user_id_%d:*", userid)
	keys := Client.Keys(context.Background(), key).Val()
	for _, v := range keys {
		ShopMap := Client.HGetAll(context.Background(), v).Val()
		user_id, _ := strconv.Atoi(ShopMap["user_id"])
		goods_id, _ := strconv.Atoi(ShopMap["goods_id"])
		goods_name := ShopMap["goods_name"]
		goods_price, _ := strconv.ParseFloat(ShopMap["goods_price"], 64)
		num, _ := strconv.Atoi(ShopMap["num"])
		shopList = append(shopList, &cart.ShopList{
			Userid:     int64(user_id),
			Goodsid:    int64(goods_id),
			Goodsname:  goods_name,
			Goodsprice: float32(goods_price),
			Num:        int64(num),
		})
	}
	return
}
